package com.tuling.code.jvm.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {
	private String name;
	private String path;

	public MyClassLoader(String name, String path) {
		super();//让系统类加载器（AppClassLoader）成为自己的父类加载器
		this.name = name;
		this.path = path;
	}
	
	public MyClassLoader(String name,String path,ClassLoader parent) {
		super(parent);  //将传入的加载器设置为自己的父类加载器
		this.name = name;
		this.path = path;
	}

	@Override
	protected Class<?> findClass(String className) throws ClassNotFoundException{
		byte[] data = readCLassFileToByteArray(className);
		return defineClass(className, data, 0, data.length);
	}

	private byte[] readCLassFileToByteArray(String fileName) throws ClassNotFoundException{
		fileName = fileName.replaceAll("\\.", "/");
		String filePath = this.path + fileName + ".class";
		File file = new File(filePath);
		
		if(!file.exists()){
			throw new ClassNotFoundException("类未找到");
		}
		
		InputStream is = null;
		byte[] returnData = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		
		
		try {
			is = new FileInputStream(file);
			int tmp = 0;
			while((tmp = is.read())!= -1){
				bos.write(tmp);
			}
			returnData = bos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
				bos.close();
			} catch (Exception e2) {
			}
		}
		return returnData;
	}
	
	@Override
	public String toString() {
		return this.name;
	}
}
